package com.hegongda.servlet;

import com.hegongda.bean.User;
import com.hegongda.service.UserService;
import com.hegongda.utils.BeanFactory;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

@WebServlet(value = "/userServlet")
public class UserServlet extends BaseServlet {
    private UserService us = BeanFactory.newInstance(UserService.class);
    //用户名重复判定
    public void hasUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("username");
        User user = us.hasUser(name);
        Result result;
        if(user == null) {
            result = new Result(Result.SUCCESS, "用户名可用");
        }
        else{
            result = new Result(Result.FAILS, "用户名重复，换一个试试");
        }
        response.getWriter().print(JSONObject.fromObject(result));
    }
    //用户注册
    public void userRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Map<String, String[]> map = request.getParameterMap();
        String code = request.getParameter("code");
        String code_session = (String)request.getSession().getAttribute("code_session");
        if (!code_session.equalsIgnoreCase(code)) {
            request.setAttribute("Error","验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }
        User user = new User();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        user.setUid(UUID.randomUUID().toString().replace("-", ""));
        user.setState(1);
        user.setCode(0);
        int i = us.userRegister(user);
        if (i == Result.SUCCESS) {
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        } else {
            request.setAttribute("Error","注册失败");
            request.getRequestDispatcher("register.jsp").forward(request,response);
        }

    }
    //用户登录
    public void userLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String rember = request.getParameter("rember");
        String aoutLogin = request.getParameter("aoutLogin");
        String code = request.getParameter("code");
        String code_session = (String)request.getSession().getAttribute("code_session");
        if (!code_session.equalsIgnoreCase(code)) {
            Result re = new Result(Result.FAILS, "验证码错误");
            response.getWriter().write(JSONObject.fromObject(re).toString());
            return;
        }
        User user = us.userLogin(name, password);
        if (user == null) {
            Result re = new Result(Result.FAILS, "用户名或密码错误");
            response.getWriter().write(JSONObject.fromObject(re).toString());
            return;
        }
        else {
            request.getSession().setAttribute("user", user);
            Cookie showuser = new Cookie("uname", URLEncoder.encode(user.getName(), "utf-8"));
            showuser.setPath(request.getContextPath());
            response.addCookie(showuser);
            Cookie Sess = new Cookie("JSESSIONID", request.getSession().getId());
            Sess.setPath(request.getContextPath());
            response.addCookie(Sess);
            if(rember != null){
                Cookie cookie1 = new Cookie("u",URLEncoder.encode(user.getUsername(), "utf-8"));
                cookie1.setMaxAge(60*10);
                cookie1.setPath(request.getContextPath());
                response.addCookie(cookie1);
                Cookie cookie2 = new Cookie("p",URLEncoder.encode(user.getPassword(), "utf-8"));
                cookie2.setMaxAge(60*10);
                cookie2.setPath(request.getContextPath());
                response.addCookie(cookie2);
                if(aoutLogin != null){
                    Cookie cookie3 = new Cookie("autlogin","autlogin");
                    cookie3.setMaxAge(60*10);
                    cookie3.setPath(request.getContextPath());
                    response.addCookie(cookie3);
                }
            }
            //查询到用户,登录成功
            Result re = new Result(Result.SUCCESS, "登录成功");
            response.getWriter().write(JSONObject.fromObject(re).toString());
        }
    }
    //退出登录
    public void userLoginOut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getSession().invalidate();
        Cookie cookie = new Cookie("username",null);
        cookie.setMaxAge(0);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        Cookie cookie1 = new Cookie("JSESSIONID",null);
        cookie1.setMaxAge(0);
        cookie1.setPath(request.getContextPath());
        response.addCookie(cookie1);

        Cookie cookie2 = new Cookie("autlogin",null);
        cookie2.setMaxAge(0);
        cookie2.setPath(request.getContextPath());
        response.addCookie(cookie2);

        Cookie cookie3 = new Cookie("u",null);
        cookie3.setMaxAge(0);
        cookie3.setPath(request.getContextPath());
        response.addCookie(cookie3);

        Cookie cookie4 = new Cookie("p",null);
        cookie4.setMaxAge(0);
        cookie4.setPath(request.getContextPath());
        response.addCookie(cookie4);

        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }

}
